package com.syezon.wifikey.news;

import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;

import com.hodanet.appadvplatclient.ad.AdInfo;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.syezon.android.base.utils.AppUtils;
import com.syezon.wifikey.R;
import com.syezon.wifikey.ad.AdPositionEnum;
import com.syezon.wifikey.ad.CommonAdViewModel;
import com.syezon.wifikey.ad.ConfigService;
import com.syezon.wifikey.base.BaseFragment;
import com.syezon.wifikey.news.adapter.SurfingHotNewsAdapter;
import com.syezon.wifikey.news.info.NewsItemInfo;
import com.syezon.wifikey.news.viewmodel.NewsViewModel;
import com.syezon.wifikey.speed.SpeedTestResult;
import com.syezon.wifikey.utils.StatusBarUtil;


import java.util.List;

import butterknife.BindView;

public class NewsListFragment extends BaseFragment implements OnRefreshLoadMoreListener {

    public static final String ARG_RESULT_INFO = "result_info";

    @BindView(R.id.cl_news_content)
    CoordinatorLayout mClTop;
//    @BindView(R.id.collapsingToolbar)
//    CollapsingToolbarLayout mCollapsingBar;
//
//    @BindView(R.id.appbarlayout)
//    AppBarLayout mAppBarLayout;

    @BindView(R.id.interceptLinearlayout)
    InterceptLinearLayout mInterceptLayout;

    @BindView(R.id.rl_actionbar)
    RelativeLayout mRlActionBar;

    @BindView(R.id.fl_result_container)
    FrameLayout mFlResultContainer;

    @BindView(R.id.refresh_layout)
    SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.rv_news_list)
    RecyclerView mRvNewsList;
    private SurfingHotNewsAdapter mAdapter;
    private NewsViewModel mNewsViewModel;
    private CommonAdViewModel mNewsTopAdViewModel;

    private Handler mHandler = new Handler();

    public NewsListFragment() {
    }


    public static NewsListFragment newInstance(ResultInfo resultInfo) {
        NewsListFragment fragment = new NewsListFragment();
        Bundle args = new Bundle();
//        args.putBoolean(ARG_SHOW_RESULT, showResult);
        args.putParcelable(ARG_RESULT_INFO, resultInfo);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.app_news_fragment_list;
    }

    @Override
    protected void initViewsAndEvents() {
        StatusBarUtil.setPaddingSmart(getContext(), mClTop);
//        mAppBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
//            @Override
//            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
//                appBarLayout.getHeight();
//            }
//        });
        mInterceptLayout.setInterceptCallBack(null);
        mRvNewsList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    mFlResultContainer.setVisibility(View.GONE);
                    mRlActionBar.setVisibility(View.VISIBLE);
                }
            }
        });
        mNewsViewModel = ViewModelProviders.of(this).get(NewsViewModel.class);
        mRvNewsList.setLayoutManager(new LinearLayoutManager(getContext()));
        mAdapter = new SurfingHotNewsAdapter(getContext());
        mRvNewsList.setAdapter(mAdapter);
        mRefreshLayout.setOnRefreshLoadMoreListener(this);
        mNewsTopAdViewModel = ViewModelProviders.of(this).get(CommonAdViewModel.class);
        mNewsTopAdViewModel.setAdPositionEnum(AdPositionEnum.NEWS_TOP_LIST);
        mNewsTopAdViewModel.getAdLiveData().observe(this, new Observer<List<AdInfo>>() {
            @Override
            public void onChanged(@Nullable List<AdInfo> adInfos) {
                if (ConfigService.getInstance().isShowSelfAd()){
                mAdapter.setTopAdInfo(adInfos);}
            }
        });
        mNewsViewModel.getRefreshMutableLiveData().observe(this, new Observer<List<NewsItemInfo>>() {
            @Override
            public void onChanged(@Nullable List<NewsItemInfo> newsItemInfos) {
                if (newsItemInfos.size() > 0) {
                    toggleShowLoading(false, "");
                    mAdapter.setData(newsItemInfos);
                    mRefreshLayout.finishRefresh();
                } else {
                    toggleShowError(true, "数据获取异常!", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            refresh();
                        }
                    });
                }

            }
        });
        mNewsViewModel.getLoadMoreMutableLiveData().observe(this, new Observer<List<NewsItemInfo>>() {
            @Override
            public void onChanged(@Nullable List<NewsItemInfo> newsItemInfos) {
                if (newsItemInfos.size() > 0) {
                    mAdapter.addData(newsItemInfos);
                    mRefreshLayout.finishLoadMore();
                } else {
                    mRefreshLayout.finishLoadMore(false);
                }
            }
        });
        refresh();
        Bundle arguments = getArguments();
        if (arguments != null) {
            ResultInfo resultInfo = arguments.getParcelable(ARG_RESULT_INFO);
            showResult(resultInfo);
        }
    }

    @Override
    public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
        super.onViewStateRestored(savedInstanceState);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            mFlResultContainer.setVisibility(View.GONE);
        }
    }

    public void showResult(ResultInfo resultInfo) {
        try {
//            mAppBarLayout.getTotalScrollRange();
            mInterceptLayout.setInterceptCallBack(null);
            if (resultInfo != null) {
                mInterceptLayout.setInterceptCallBack(new InterceptLinearLayout.InterceptCallBack() {
                    @Override
                    public boolean onIntercept() {
                        return true;
                    }

                    @Override
                    public void consume() {
                        mRlActionBar.setVisibility(View.VISIBLE);
                        mFlResultContainer.setVisibility(View.GONE);
                        mInterceptLayout.setInterceptCallBack(null);
                    }
                });
                mRlActionBar.setVisibility(View.GONE);
                mFlResultContainer.setVisibility(View.VISIBLE);
                int resultType = resultInfo.getResultType();
                if (ResultInfo.RESULT_TYPE_SPEED_UP == resultType) {
                    int add = resultInfo.getAdd();
                    getChildFragmentManager().beginTransaction().replace(R.id.fl_result_container, SpeedUpResultFragment.newInstance(add)).commitAllowingStateLoss();
                }
                if (ResultInfo.RESULT_TYPE_SPEEDTEST == resultType) {
                    SpeedTestResult speedTestResult = resultInfo.getSpeedTestResult();
                    getChildFragmentManager().beginTransaction().replace(R.id.fl_result_container, SpeedTestResultFragment.newInstance(speedTestResult)).commitAllowingStateLoss();
                }
                if (ResultInfo.RESULT_TYPE_WIFI_ENHANCE == resultType) {
                    String ssid = resultInfo.getSsid();
                    getChildFragmentManager().beginTransaction().replace(R.id.fl_result_container, WifiEnhanceResultFragment.newInstance(ssid)).commitAllowingStateLoss();
                }
                if (ResultInfo.RESULT_TYPE_WIFI_SAFE == resultType) {
                    getChildFragmentManager().beginTransaction().replace(R.id.fl_result_container, WifiSafeResultFragment.newInstance()).commitAllowingStateLoss();
                }
                if (ResultInfo.TYPE_SHOW_WIFI_INFO == resultType) {
                    String ssid = resultInfo.getSsid();
                    getChildFragmentManager().beginTransaction().replace(R.id.fl_result_container, WifiInfoFragment.newInstance(ssid)).commitAllowingStateLoss();
                }
                resultInfo.setShowResult(false);
            } else {
                mRlActionBar.setVisibility(View.VISIBLE);
                mFlResultContainer.setVisibility(View.GONE);
            }
        } catch (Exception e) {

        }

    }

    private void refresh() {
        toggleShowLoading(true, "正在加载...");
        mNewsViewModel.refreshNews(true);
    }

    @Override
    protected View getLoadingTargetView() {
        return mRefreshLayout;
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        mNewsViewModel.refreshNews(true);
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        mNewsViewModel.loadMoreNews();
    }
}
